<?php
/**
 * Created by PhpStorm.
 * User: charles
 * Date: 2017-11-4
 * Time: 21:03
 */

namespace App\Models;


use Carbon\Carbon;

class WechatPay
{
    private $amount = 0;
    private $openid = '';
    private $orderAttributes = [];
    private $order = null;


    public function __construct($amount, $openid, $order)
    {
        $this->amount = $amount;
        $this->openid = $openid;
        $this->order = $order;
    }

    private function prepareOrderAttributes()
    {
        $domain = SettingsCache::get('WECHAT_DOMAIN');
        $this->orderAttributes = [
            'appid'            => 'wx55aaf24641c5c003',
            'mch_id'           => '1491076612',
            'trade_type'       => 'JSAPI',
            'body'             => '红透透商务-二手手机远程估价服务',
            'time_expire'      => (string) Carbon::now()->addYear(1)->format('YmdHis'),
            'out_trade_no'     => $this->order->number,
            'total_fee'        => (int) 100 * $this->amount, // 单位：分
            'notify_url'       => "http://{$domain}/wechat/payment/notify", // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid'           => $this->openid,
            'spbill_create_ip' => \EasyWeChat\Payment\get_client_ip(),
        ];
    }

    public function getPrepayId()
    {
        $prepayId = $this->order->prepare_id;
        if (empty($prepayId)) {
            if ($this->orderAttributes['spbill_create_ip'] == '::1' || $this->orderAttributes['spbill_create_ip'] == '127.0.0.1') {
                $this->orderAttributes['spbill_create_ip'] = '120.204.77.4';
            }
            $order = new \EasyWeChat\Payment\Order($this->orderAttributes);
            $orderResult = EasyWechat::getApp()
                ->payment
                ->prepare($order);
            if ($orderResult->return_code == 'SUCCESS' && $orderResult->result_code == 'SUCCESS') {
                $prepayId = $orderResult->prepay_id;
                $this->order->prepare_id = $prepayId;
                $this->order->save();
            } else {
                abort(400, '微信支付出错：' . $orderResult->return_msg);
            }
        }
        return $prepayId;
    }

    public function configForPayment($prepayId) : string
    {
        return EasyWechat::getApp()->payment->configForPayment($prepayId);
    }

    public function getPaymentJsonString() : string
    {
        $this->prepareOrderAttributes();
        $prepayId = $this->getPrepayId();
        if (0 === $prepayId) {
            abort(400, '微信支付出错');
        }
        return $this->configForPayment($prepayId);
    }
}